/**
 * @name: fetch.js
 * @description: 请求方法定义
 * @author: 温永江
 * @create: 2020/07/22 14:13:01
 * @update: 2020/07/22 14:13:01
 */
 import Vue from 'vue';
 // import main from '@/main.js';
 import router from '@/router/';
 import axios from 'axios';
 // eslint-disable-next-line
 import { stringify } from 'qs';
/**
 * 190020 二清 - OCR识别与企业工商认证信息已通过 
 * 190021 二清 - OCR识别与企业法人实名信息已通过
 * 
 * */  
 const specialCode = [190020, 190021]

const time = 3000;
let obj = {};
const getToken = async () => {
  const login = await Vue.lf.getItem('login');
  const menu = await Vue.lf.getItem('menu');
  if (login) {
    obj.token = `Bearer ${login.accessToken}`;
    if (menu) {
      if (menu && menu.ascriptionCustomerCode) {
        obj.ascriptionCustomerCode = menu.ascriptionCustomerCode;
      } else if (menu && !menu.ascriptionCustomerCode) {
        delete obj.ascriptionCustomerCode;
      }
      if (menu && menu.currentRoleType && menu.currentRoleType.roleTypeCode) {
        obj.currentRoleType = menu.currentRoleType.roleTypeCode;
      } else {
        delete obj.currentRoleType;
      }
    }
    return obj;
  }
  return null;
};
const goLogin = () => {
  // 跳转登录页方法
  Vue.controller.login();
};
let Token = '';
axios.interceptors.request.use(
  config => {
    // 发送请求之前做一些处理
    const isFd = config.type.toLowerCase() == 'formdata';
    let myConfig = config;
    // 当数据时formData类型时，不要对config.data做任何普通对象的处理
    // 保持其formData的类型不变
    if (myConfig.data == '[object Object]') {
      for (let key in myConfig.data) {
        if (myConfig.data[key] === undefined) {
          myConfig.data[key] = '';
        }
      }
      let tem = JSON.parse(JSON.stringify(myConfig.data));
      myConfig.data = {};
      myConfig.data = tem;
    }
    return getToken().then(login => {
      // if (!!token && !isFd) {
      //   myConfig.data = { ...myConfig.data };
      // } else if (isFd) myConfig.data.append('token', token);
      if (login && login.token) {
        myConfig.headers = {
          'Content-Type': 'application/json',
          "Authorization": login.token
          // 'Content-Type': 'application/x-www-form-urlencoded'
        };
      }
      if (login && login.ascriptionCustomerCode) {
        myConfig.headers.AscriptionCustomerCode = login.ascriptionCustomerCode;
      } else if (login && !login.ascriptionCustomerCode) {
        delete myConfig.headers.AscriptionCustomerCode;
      }
      if (login && login.currentRoleType) {
        myConfig.headers.CurrentRoleType = login.currentRoleType;
      } else if (login && !login.currentRoleType) {
        delete myConfig.headers.CurrentRoleType;
      }
      // 处理formdata
      if (config.type.toLowerCase() == 'formdata') {
        // myConfig.headers = {
        //   'Content-Type': 'multipart/form-data'
        // };
        myConfig.headers['Content-Type'] = 'multipart/form-data';
      }
      // console.log(config)
      myConfig.baseURL = config.baseUrl || window.__CONFIG__.url; // 网站接口前缀
      // myConfig.baseURL = 'http://router-gateway.test.yuoucn.cn:50000';
      myConfig.method = 'POST';
      // config.data.token =
      //   config.data.token ||
      //   localStorage.token ||
      //   parse(url.parse(location.href).query).token
      myConfig.timeout = 50000;
      // if (router.currentRoute.name == "login") {
      //   delete config.data.token
      // }
      if (config.type.toLowerCase() != 'formdata') {
        // myConfig.data = stringify(config.data);
      } else {
      }
      return myConfig;
    });
  },
  error => {
    // 当请求异常时做一些处理
    console.log('请求出错');

    return Promise.reject(error);
  }
);

// 响应时拦截
axios.interceptors.response.use(
  response =>
    // 返回响应时做一些处理
    response,
  error => {
    if (!error.response) {
      Vue.tips({
        content: '网络中断，请检查！',
        type: 'error'
      }).hide(time);
    }
    Vue.loading().hide();
    return Promise.reject(error);
  }
);
// 检索特定code值
const checkCode = (code, resParams, promiseState) => {
  const { resolve, reject } = promiseState;
  let givenCodes = [
    { givenCode: '190014', message: '供货提交成功。但分类保证金不足，可能导致审核失败，请尽快缴纳' }
  ];
  let result = givenCodes.filter(item => item.givenCode === code.toString());
  if (result.length !== 0) {
    resolve(resParams.data);
    Vue.tips({
      content: resParams.data.message || result[0].message,
      type: 'error'
    })
      .show()
      .hide(time);
    Vue.lf.setItem('recentlyResponseTime', new Date() - 0);
  } else {
    Vue.tips({
      content: resParams.data.message,
      type: 'error'
    }).hide(time);
    reject(resParams.data.Msg);
  }
};
export default function ({
  baseUrl,
  api,
  para = {},
  loading = false,
  loadingText = '加载中...',
  type = 'json',
  isSuccessTip = false,
  isBlob = false,
  filename = '',
  progressCallback = () => { }
}) {
  return getToken().then(login => {
    Token = login ? login.token : "";
    // 前置处理：如果检测到token为空，则不发请求，直接回登陆页
    if (!Token && router.currentRoute.name !== 'login') {
      // Vue.lf.removeItem('keepQuickMenu').then(goLogin);
    }
    if (loading) {
      Vue.loading({
        content: loadingText
      }).show();
    }
    return new Promise((resolve, reject) => {
      let setting = {
        method: 'post',
        baseUrl,
        url: api,
        data: para,
        type
      };
      if (isBlob) {
        setting.responseType = 'blob';
      }
      // formdata 上传数据是否做进度显示处理
      if (type.toLowerCase() == 'formdata' && typeof progressCallback == 'function') {
        setting.onUploadProgress = progressCallback;
      }
      // console.log(para);

       axios(setting)
         .then(res => {
           loading && Vue.loading().hide();
           if (isBlob) {
             const blob = new Blob([res.data]);
             const downloadElement = document.createElement('a');
             const href = window.URL.createObjectURL(blob); // 创建下载的链接
             downloadElement.href = href;
             downloadElement.download = `${filename}.xlsx`; // 下载后文件名
             document.body.appendChild(downloadElement);
             downloadElement.click(); // 点击下载
             document.body.removeChild(downloadElement); // 下载完成移除元素
             window.URL.revokeObjectURL(href); // 释放掉blob对象
             resolve();
           } else {
             switch (parseInt(res.data.code)) {
               case 200:
                 if (type.toLowerCase() == 'formdata') {
                   resolve(res.data);
                 } else {
                   resolve(res.data.data);
                 }
                 if (isSuccessTip && res.data.message) {
                   Vue.tips({
                     content: res.data.message,
                     type: 'success'
                   })
                     .show()
                     .hide(time);
                 }
                 // 记录最近一次请求响应成功的时间
                 Vue.lf.setItem('recentlyResponseTime', new Date() - 0);
                 break;
               case 401:
                 Vue.tips({
                   content: res.data.message,
                   type: 'error'
                 })
                   .show()
                   .hide(time);
                 reject(res);
                 Vue.lf.removeItem('login');
                 Vue.lf.getItem('recentlyResponseTime').then(t => {
                   if (t) {
                     const d = new Date() - t;
                     // 如果大于2小时，则不保留快捷页签
                     if (d > 2 * 3600 * 1000) {
                       Vue.lf.removeItem('keepQuickMenu').then(goLogin);
                     } else {
                       Vue.lf.setItem('keepQuickMenu', 1).then(goLogin);
                     }
                   } else {
                     goLogin();
                   }
                 });
                 break;
               default:
                 /// specialCode - 后端返回不同code抛出res 页面判断逻辑
                 if (specialCode.length > 0 && specialCode.indexOf(res.data.code) !== -1) {
                    resolve(res.data)
                    return
                 }
                 checkCode(parseInt(res.data.code), res, { resolve, reject });
                 // Vue.tips({
                 //   content: res.data.message,
                 //   type: 'error'
                 // }).hide(time);
                 // reject(res.data.Msg);
             }
           }
         })
         .catch(err => {
           switch (parseInt(err.response.data.code)) {
             case 401:
               Vue.tips({
                 content: err.response.data.message,
                 type: 'error'
               })
                 .show()
                 .hide(time);
               reject(err);
               Vue.lf.removeItem('login');
               Vue.lf.getItem('recentlyResponseTime').then(t => {
                 if (t) {
                   const d = new Date() - t;
                   // 如果大于2小时，则不保留快捷页签
                   if (d > 2 * 3600 * 1000) {
                     Vue.lf.removeItem('keepQuickMenu').then(goLogin);
                   } else {
                     Vue.lf.setItem('keepQuickMenu', 1).then(goLogin);
                   }
                 } else {
                   goLogin();
                 }
               });
               break;
             default:
               Vue.tips({
                 content: err.response.data.message,
                 type: 'error'
               }).hide(time);
               reject(err.response.data.message);
           }
         });
     });
   });
 }